package org.irri.smta.ui.sorter;

import java.lang.reflect.Field;
import java.util.Comparator;

import org.irri.smta.domain.SmtaReport;
import org.primefaces.model.SortOrder;

public class SmtaReportLazySorter implements Comparator<SmtaReport> {

    private String sortField;
    
    private SortOrder sortOrder;
    
    public SmtaReportLazySorter(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public int compare(SmtaReport o1, SmtaReport o2) {
        try {
        	Field field = SmtaReport.class.getDeclaredField(this.sortField);
        	field.setAccessible(true);
            Object value1 = field.get(o1);
            Object value2 = field.get(o2);

            int value = ((Comparable)value1).compareTo(value2);
            
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

}
